package com.ctsi.sms.app.rest;

import com.ctsi.sms.BaseMessage;
import com.ctsi.sms.common.util.ChannelUtil;
import com.ctsi.sms.entity.SmsEntity;
import com.ctsi.sms.service.SmsService;
import com.ctsi.sms.service.ZzzxSMGPEndPoint;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SmsController {

    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsService smsService;

    /**
     * 发送短信接口
     *
     * @param sms
     * @return
     */
    @PostMapping(value = "/smsclient/send", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
    public void querySmsList(@RequestBody SmsEntity sms) {
        BaseMessage msg = ZzzxSMGPEndPoint.createMessage(sms.getMlcontent(), sms.getPmoblie());
        try {
            ChannelFuture promises = ChannelUtil.asyncWriteToEntity(ZzzxSMGPEndPoint.SMS_CLIENT_ID, msg, null);
            promises.addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    if (future.isSuccess()) {
                        logger.warn("sms send to {} success!",sms.getPmoblie());
                        // TODO: 短信发送成功，写入数据库
                        sms.setMlstate(1);
                        smsService.insertSms(sms);
                    } else {
                        logger.warn("sms send to {} faild!",sms.getPmoblie());
                        String err = future.cause().getMessage();
                        // TODO：短信发送失败，写入数据库
                        sms.setMlstate(0);
                        smsService.insertSms(sms);
                    }
                }
            });
        } catch (Exception e) {
            logger.error("send sms occur error: {}", e);
        }
    }


}
